package fr.cephb.berkeley.baseapi.db;

import java.io.FileNotFoundException;

import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseConfig;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.LockMode;
import com.sleepycat.db.OperationStatus;
import com.sleepycat.db.Transaction;

import fr.cephb.berkeley.baseapi.bindings.TupleBinding;


/**
 * PrimaryDB
 * @author pierre
 *
 * @param <K>
 * @param <V>
 */
public class PrimaryDB<K,V>
	extends BerkeleyDB<K,V>
	{
	private Database database;

	/**
	 * PrimaryDB
	 * @param env
	 * @param txn
	 * @param filename
	 * @param databaseName
	 * @param dbConfig
	 * @param keyBinding
	 * @param valueBinding
	 * @throws DatabaseException
	 * @throws FileNotFoundException
	 */
	public PrimaryDB(
			Environment env,
			Transaction txn,
			String filename,
			String databaseName,
			DatabaseConfig dbConfig,
			TupleBinding<K> keyBinding,
			TupleBinding<V> valueBinding
			) throws DatabaseException,FileNotFoundException
		{
		super(keyBinding,valueBinding);
		dbConfig=defaultDbCfg(env,dbConfig);
		if(dbConfig.getSortedDuplicates()) throw new IllegalArgumentException();
		if(filename==null) throw new IllegalArgumentException("filename is null");
		this.database= env.openDatabase(txn, filename,databaseName,dbConfig);
		}
	
	public boolean containsKey(Transaction txn,K key) throws DatabaseException
		{
		return getDatabase().get(txn, keyToEntry(key), new DatabaseEntry(), LockMode.DEFAULT)==OperationStatus.SUCCESS;
		}
	
	public V get(Transaction txn,K key) throws DatabaseException
		{
		DatabaseEntry data= new DatabaseEntry();
		return
			getDatabase().get(txn, keyToEntry(key), data, LockMode.DEFAULT)!=OperationStatus.SUCCESS
			?  null: entryToValue(data);
		}

	
	public Database getDatabase()
		{
		return this.database;
		}
	
	}
